package com.smart.seven.aop.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib代理类
 *
 * @author junrui.wang
 * @create 2018/7/24
 */
public class CglibProxy implements MethodInterceptor {
    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clazz){
        //设置需要创建子类的类
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        //通过字节码技术动态创建子类实例
        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        //开始对方法进行性能监视
        PerformanceMonitor.begin(o.getClass().getName() + "." + method.getName());

        //通过代理类调用父类中的方法
        Object result = methodProxy.invokeSuper(o, args);

        //结束对方法的性能监视
        PerformanceMonitor.end();

        return result;
    }
}
